package com.tarena.lbs.basic.web.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.web.dao.repository.AdminRepository;
import com.tarena.lbs.basic.web.pojo.param.AddAdminParam;
import com.tarena.lbs.basic.web.pojo.param.QueryAdminParam;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.vo.AdminVO;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.joda.time.LocalDate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class AdminService {

    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;

    @Autowired
    private AdminRepository adminRepository;


    public AdminVO getAdminDetailInfo(String jwt) throws BusinessException {
        log.debug("jwt:{}",jwt);
        Integer adminId = getAdminId(jwt);
        AdminPO adminPO = adminRepository.getById(adminId);
        if (adminPO!=null){
            AdminVO adminVO = new AdminVO();
            BeanUtils.copyProperties(adminPO,adminVO);
            return adminVO;
        }
        return null;
    }


    public Integer getAdminId(String jwt) throws BusinessException {
        if (jwt!=null && jwt.length()>0){
            UserPrinciple userPrinciple = jwtEncoder.getLoginFromToken(jwt, UserPrinciple.class);
            return userPrinciple.getId();
        }
        return null;
    }

    public PageResult<AdminVO> getAdminPage(QueryAdminParam queryAdminParam) {
        PageResult<AdminVO> pageResult = new PageResult<>();
        pageResult.setPageNo(queryAdminParam.getPageNo());
        pageResult.setPageSize(queryAdminParam.getPageSize());
        List<AdminVO> collect = adminRepository.getAdminVOS(queryAdminParam,pageResult);
        pageResult.setObjects(collect);
        return pageResult;
    }


    public void addAdmin(AddAdminParam addAdminParam) throws BusinessException {
        AdminPO adminPO = new AdminPO();
        adminPO.setCreateTime(new Date());
        adminRepository.check(addAdminParam);
        BeanUtils.copyProperties(addAdminParam,adminPO);
        adminRepository.save(adminPO);
        log.debug("新增管理员成功 adminPO={}",adminPO);
    }




}
